//
//  HomeManageViewController.m
//  xpkc
//
//  Created by wanmeizty on 14/12/24.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "HomeManageViewController.h"

@interface HomeManageViewController ()

@end

@implementation HomeManageViewController{
    UIScrollView *scrollView;
    //数据
    NSMutableArray *allArray;
    NSMutableArray *catalogueInArray;
    NSMutableArray *catalogueOutArray;
    //按钮
    NSMutableArray *btnInArray;
    NSMutableArray *btnOutArray;
    
    
    CGPoint startPoint;
    UIButton *tempBtn;
    CGRect tempFrame;
    CGFloat xx;//偏移距离
    CGFloat yy;
    int xP;//偏移单位
    int yP;
    int startIndex;//起始按钮数组位置
    int stopIndex;
    //常用栏目距离顶部高度
    int top;
    //不常用栏目距离顶部距离
    int top2;
    CGFloat buttonW;//按钮宽度
    CGFloat buttonH;
    int numLine;//每行个数
    CGFloat spaceSize;//间隔大小
    
    UILabel *_label3;
    UILabel *_label4;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatView];
}
#pragma mark -
#pragma mark == creatview ==
/**
 *  创建视图
 */
-(void)creatView{
    if (isPad) {
        spaceSize = 40;
        numLine = 4;
    }else{
        spaceSize = 20;
        numLine = 3;
    }
    top = spaceSize;
    top2 = 210;
    
    buttonW = (SCREEN_WIDTH-spaceSize*(numLine+1))/numLine;
    buttonH = buttonW/2;
    
    scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    
    scrollView.showsVerticalScrollIndicator = FALSE;
    scrollView.backgroundColor = BGColor;
    scrollView.userInteractionEnabled = YES;
    
    
    [self.view addSubview:scrollView];
    //开始获取
    [self getLocalCatelogueInfo];
}

/**
 *  创建导航栏按钮
 */
- (void)creatNavItem{
    [super creatNavItem];
    
    UIBarButtonItem *manageBtn = [[UIBarButtonItem alloc]initWithTitle:@"更新" style:UIBarButtonItemStyleBordered target:self action:@selector(catalogueRefresh)];
    [manageBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = manageBtn;
}

/**
 *  界面赋值
 */
-(void)creatHomeBtn{
    
    if (isPad) {
        top2 =((catalogueInArray.count+3)/4)*(buttonH+spaceSize)+100;
    }else{
        top2 =((catalogueInArray.count+2)/3)*(buttonH+spaceSize)+70;
    }
    
    UILabel *label = [[UILabel alloc]init];
    label.text = @"常用栏目·";
    label.frame = CGRectMake(0, 0, 100, 50);
    label.font = [UIFont boldSystemFontOfSize:14];
    [scrollView addSubview:label];
    
    UILabel *label2 = [[UILabel alloc]init];
    label2.text = @"长按可拖动调整栏目顺序";
    label2.frame = CGRectMake(70, 0, 200, 50);
    label2.font = [UIFont systemFontOfSize:12];
    [scrollView addSubview:label2];
    
    _label3 = [[UILabel alloc]init];
    _label3.text = @"其他栏目·";
    _label3.frame = CGRectMake(0, top2-20, 100, 30);
    _label3.font = [UIFont boldSystemFontOfSize:14];
    [scrollView addSubview:_label3];
    
    _label4 = [[UILabel alloc]init];
    _label4.text = @"点击可添加至常用栏目";
    _label4.frame = CGRectMake(70, top2-20, 200, 30);
    _label4.font = [UIFont systemFontOfSize:12];
    [scrollView addSubview:_label4];
    
    scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (catalogueInArray.count+2)/2*(buttonH+spaceSize)+spaceSize);
    
    for (int i = 0; i<catalogueInArray.count; i++) {
        NSDictionary *dic = [catalogueInArray objectAtIndex:i];
        
        HomeButton *homeBtn = [[HomeButton alloc]initWithFrame:CGRectMake(0, 0, buttonW, buttonH)];
        homeBtn.buttonTitle = [dic objectForKey:@"title"];
        homeBtn.enterType = [dic objectForKey:@"enterType"];
        homeBtn.enterIndex = [dic objectForKey:@"index"];

        [homeBtn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        [homeBtn addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touch:)];
        [homeBtn addGestureRecognizer:longPress];
        [homeBtn isInHome:YES];
        [homeBtn setValue];
        [homeBtn setStyle:HomeButtonStyleLightGray];
        if ([[dic objectForKey:@"enterType"] isEqualToString:@"more"]) {
            homeBtn.userInteractionEnabled = NO;
            homeBtn.backgroundColor = [UIColor darkGrayColor];
        }
        
        [btnInArray addObject:homeBtn];
//        logdebug(@"%@",btnInArray);
        [scrollView addSubview:homeBtn];
    }
    for (int i = 0; i<catalogueOutArray.count; i++) {
        NSDictionary *dic = [catalogueOutArray objectAtIndex:i];
        
        HomeButton *homeBtn = [[HomeButton alloc]initWithFrame:CGRectMake(0, 0, buttonW, buttonH)];
        homeBtn.buttonTitle = [dic objectForKey:@"title"];
        homeBtn.enterType = [dic objectForKey:@"enterType"];
        homeBtn.enterIndex = [dic objectForKey:@"index"];
        [homeBtn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top2+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        [homeBtn addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(touch:)];
        [homeBtn addGestureRecognizer:longPress];
        [homeBtn isInHome:NO];
        [homeBtn setValue];
        [homeBtn setStyle:HomeButtonStyleLightGray];
        
        [btnOutArray addObject:homeBtn];
        [scrollView addSubview:homeBtn];
    }
}

#pragma mark -
#pragma mark == func ==

/**
 *  获取本地的目录信息
 */
-(void)getLocalCatelogueInfo{
    //初始化
    btnInArray = [NSMutableArray array];
    btnOutArray = [NSMutableArray array];
    allArray = [NSMutableArray array];
    catalogueInArray = [NSMutableArray array];
    catalogueOutArray = [NSMutableArray array];
    if (1) {
        catalogueInArray = self.inArray;
        catalogueOutArray = self.outArray;
    }else{
        //FIXME:请求网络的时候以后修改
        [self catalogueRefresh];
    }
    [self creatHomeBtn];
}

/**
 *  设定位置
 */
- (void)setBtnFrame{
    if (isPad) {
        top2 =((btnInArray.count+3)/4)*(buttonH+spaceSize)+100;
    }else{
        top2 =((btnInArray.count+2)/3)*(buttonH+spaceSize)+70;
    }
    int j = 0;
    for (int i = 0; i<btnInArray.count; i++) {
        UIButton *btn = [btnInArray objectAtIndex:i];
        //判断是否延时
        if (i%numLine*(buttonW+spaceSize)+spaceSize - btn.frame.origin.x <= 1 &&
            top+i/numLine*(buttonH+spaceSize)+spaceSize - btn.frame.origin.y <= 1) {
            //做差减少误差啊，妈蛋的小数直接比较容易出错的
            //巨坑
        }else{
            j++;
        }
        [UIView animateWithDuration:0.3 delay:j*0.1 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
            [btn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        } completion:^(BOOL finished) {
            //
        }];
    }
    j = 0;
    for (int i = 0; i<btnOutArray.count; i++) {
        UIButton *btn = [btnOutArray objectAtIndex:i];
        //判断是否延时
        if (i%numLine*(buttonW+spaceSize)+spaceSize - btn.frame.origin.x <= 1 &&
            top2+i/numLine*(buttonH+spaceSize)+spaceSize - btn.frame.origin.y <= 1) {
            //做差减少误差啊，妈蛋的小数直接比较容易出错的
            //巨坑
        }else{
            j++;
        }
        [UIView animateWithDuration:0.3 delay:j*0.1 options:UIViewAnimationOptionAllowAnimatedContent animations:^{
            [btn setFrame:CGRectMake(i%numLine*(buttonW+spaceSize)+spaceSize, top2+i/numLine*(buttonH+spaceSize)+spaceSize, buttonW, buttonH)];
        } completion:^(BOOL finished) {
            //
        }];
    }
    [UIView animateWithDuration:0.3 animations:^{
        _label3.frame = CGRectMake(0, top2-20, 100, 30);
        _label4.frame = CGRectMake(70, top2-20, 200, 30);
    }];
    
}

/**
 *  项目按钮点击
 *
 *  @param btn btn
 */
-(void)catalogueButtonClick:(HomeButton *)btn{
    if ([btnInArray containsObject:btn]) {
        
        NSUInteger index = [btnInArray indexOfObject:btn];
        [catalogueOutArray addObject:[catalogueInArray objectAtIndex:index]];
        [catalogueInArray removeObjectAtIndex:index];
        
        [btnOutArray addObject:btn];
        [btnInArray removeObject:btn];
        [btn isInHome:NO];
    }else{
        NSUInteger index = [btnOutArray indexOfObject:btn];
        [catalogueInArray insertObject:[catalogueOutArray objectAtIndex:index] atIndex:catalogueInArray.count-1];
        [catalogueOutArray removeObjectAtIndex:index];
        
        [btnInArray insertObject:btn atIndex:btnInArray.count-1];
        [btnOutArray removeObject:btn];
        [btn isInHome:YES];
    }
    [self setBtnFrame];
    
}
/**
 *  长按拖动手势
 *
 *  @param ges ges
 */
-(void)touch:(UIGestureRecognizer *)ges{
    NSMutableArray *btnTempArray;
    NSMutableArray *dicTempArray;
    CGFloat tempTop;
    int btnCount;
    BOOL isIn = NO;
    if ([btnInArray containsObject:ges.view]) {
        //
        logdebug(@"有");
        btnTempArray = btnInArray;
        dicTempArray = catalogueInArray;
        btnCount = (int)btnInArray.count;
        tempTop = top;
        isIn = YES;
    }else{
        logdebug(@"木有啊");
        btnTempArray = btnOutArray;
        dicTempArray = catalogueOutArray;
        btnCount = (int)btnOutArray.count;
        tempTop = top2;
        isIn = NO;
    }
    if (ges.state == UIGestureRecognizerStateBegan) {
        logdebug(@"长按开始");
        //记录初始数据好做坐标运算
        startPoint = [ges locationInView:scrollView];
        logdebug(@"起始坐标%f:%f",startPoint.x,startPoint.y);
        startIndex = ((int)startPoint.x/(int)(SCREEN_WIDTH/numLine)*1+(int)(startPoint.y-tempTop)/(int)(buttonH+spaceSize)*numLine);
        tempBtn = [btnTempArray objectAtIndex:startIndex];
        [scrollView bringSubviewToFront:tempBtn];
        tempFrame = tempBtn.frame;
        tempBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        tempBtn.layer.shadowOffset = CGSizeMake(10, 10);
        tempBtn.layer.shadowOpacity = 0.4;
        
    }
    xx = [ges locationInView:scrollView].x-startPoint.x;
    yy = [ges locationInView:scrollView].y-startPoint.y;
    logdebug(@"位移%f:%f",xx,yy);
    tempBtn.frame = CGRectMake(tempFrame.origin.x+xx, tempFrame.origin.y+yy, tempFrame.size.width, tempFrame.size.height);
    if (xx>=0) {
        xP = (int)(xx+(buttonW+spaceSize)/2)/(buttonW+spaceSize);
    }else{
        xP = (int)(xx-(buttonW+spaceSize)/2)/(buttonW+spaceSize);
    }
    if (yy>=0) {
        yP = (int)(yy+(buttonH+spaceSize)/2)/(buttonH+spaceSize);
    }else{
        yP = (int)(yy-(buttonH+spaceSize)/2)/(buttonH+spaceSize);
    }
    logdebug(@"位移单位%d",xP+numLine*yP);
    if (ges.state == UIGestureRecognizerStateEnded) {
        logdebug(@"长按结束");
        tempBtn.layer.borderWidth = 0;
        tempBtn.layer.shadowOffset = CGSizeMake(0, 0);
        tempBtn.layer.shadowColor = [UIColor whiteColor].CGColor;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2];
        //位移范围判定
        if (tempFrame.origin.x+xP*(buttonW+spaceSize)<=0) {
            logdebug(@"太左");
            xP = 0;
        }
        if (tempFrame.origin.x+xP*(buttonW+spaceSize)+spaceSize/2>=SCREEN_WIDTH) {
            logdebug(@"太右");
            xP = numLine-1;
        }
        if (tempFrame.origin.y+yP*(buttonH+spaceSize)<=tempTop) {
            logdebug(@"太上");
            yP = 0;
        }
        if (tempFrame.origin.y+yP*(buttonH+spaceSize) >= (buttonH+spaceSize)*((btnCount+1)/numLine)+spaceSize+tempTop) {
            logdebug(@"太往下了");
            yP = (btnCount+numLine-1)/numLine-1;
        }
        logdebug(@"移动行数%d",yP);
        //结束定一下位置
        tempBtn.frame = CGRectMake(tempFrame.origin.x+xP*(buttonW+spaceSize), tempFrame.origin.y+yP*(buttonH+spaceSize), tempFrame.size.width, tempFrame.size.height);
        [UIView commitAnimations];
        
        stopIndex = startIndex+xP+yP*numLine;
        if (stopIndex < 0) {
            stopIndex = 0;
        }
        if (isIn) {
            if (stopIndex >= btnCount-1) {
                //拖到最后了
                //不行的啊，得保证更多最后
                stopIndex = btnCount-2;
            }
        }else{
            if (stopIndex >= btnCount) {
                //底下没有最后的更多按钮
                stopIndex = btnCount - 1;
            }
        }
        logdebug(@"结束单位%d",stopIndex);
        
        if (stopIndex>startIndex) {
            //往下拉
            [btnTempArray exchangeObjectAtIndex:startIndex withObjectAtIndex:stopIndex];
            [dicTempArray exchangeObjectAtIndex:startIndex withObjectAtIndex:stopIndex];
        }else{
            [btnTempArray insertObject:tempBtn atIndex:stopIndex];
            [btnTempArray removeObjectAtIndex:startIndex+1];
            [dicTempArray insertObject:[dicTempArray objectAtIndex:startIndex] atIndex:stopIndex];
            [dicTempArray removeObjectAtIndex:startIndex+1];
        }
        [self setBtnFrame];
    }
    
}
/**
 *  目录更新
 */
-(void)catalogueRefresh{
    logdebug(@"目录管理");
    //本地文件
    //模拟数据
    NSArray *titleArray = @[@"公开课",@"备考资讯",@"选课中心",@"我的课程",@"个人中心",@"设置",@"离线管理",@"更多"];
    NSArray *typeArray = @[@"tab",@"push",@"push",@"tab",@"tab",@"push",@"push",@"more"];
    NSArray *enterindexArray = @[@"1",@"0",@"0",@"2",@"3",@"0",@"0",@"0"];
    NSArray *btnimgArray = @[@"home_opencourse",@"home_news",@"home_coursecenter",@"home_mycourse",@"home_user",@"home_set",@"home_offline",@"home_more"];
    NSArray *selectedimg = @[@"home_opencourse",@"home_news",@"home_coursecenter",@"home_mycourse",@"home_user",@"home_set",@"home_offline",@"home_more"];
    for (int i = 0; i<titleArray.count; i++) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [titleArray objectAtIndex:i],@"title",
                             [typeArray objectAtIndex:i],@"enterType",
                             [enterindexArray objectAtIndex:i],@"index",
                             [btnimgArray objectAtIndex:i],@"image",
                             [selectedimg objectAtIndex:i],@"selectImage",
                             nil];
        [allArray addObject:dic];
    }
    //TODO:1刷新列表2删除或者修改列表
    for (UIButton *btn in btnInArray) {
        [btn removeFromSuperview];
    }
}
/**
 *  保存
 *
 *  @param animated an
 */
-(void)viewWillDisappear:(BOOL)animated{
    logdebug(@"视图消失:保存目录信息");
    //TODO:保存排列好的标签顺序
    //返回按钮数组

    self.homeblock(catalogueInArray,catalogueOutArray);
}

#pragma mark -
#pragma mark == other ==

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
